import _ from "lodash";
import { Row, message, Icon, Col } from "antd";
import React from "react";
import CopyToClipboard from 'react-copy-to-clipboard';
import Directive from "./directive";
import { WeaCheckbox, WeaHelpfulTip, WeaInput, WeaLocaleProvider, WeaRichText, WeaSelect } from "ecCom";
import { getVarifyComponent } from '../../../../common/validates';
import utils from "../../../../../utils";
import { hasReadOnlyComs, comsType } from '../../../../../constants/form';

const { FORM_HEADER, ADDRESS, DATATABLE } = comsType;
const { getLabel } = WeaLocaleProvider;

const success = () => message.success(getLabel('125245', '复制成功'));
const FieldNameItem = ({name, tips, value}) => (
  <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@8rhrur`} className='wea-edc-physical-field'>
    <label>{name}</label>
    <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@qeiovd`}
      title={<div>{tips}</div>}
      placement="topRight"
    />
    <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@lebgcz`} viewAttr={1} value={value} hasBorder={true}/>
    <CopyToClipboard ecId={`${this && this.props && this.props.ecId || ''}_CopyToClipboard@1gkwlz`} text={value} onCopy={success}>
        <div title={getLabel('383573', '点击复制')} className='field-icon'><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@mfke2s`} type="copy" /></div>
    </CopyToClipboard>
  </Row>
)

export default class Props extends React.Component {
  constructor() {
    super();
    this.state = {
      addressFieldsSelVal: ''  //地址组件字段名称属性选中值
    }

    this.handlePropChange = _.memoize(this.handlePropChange.bind(this));
  }

  handlePropChange(key, handleValue = v => v, debounceTime) {
    const rewriteMethod = `handle${utils.toUpperCase(key)}Change`;

    if (this[rewriteMethod]) return this[rewriteMethod];

    const directive = new Directive(key, this);

    if(_.isNumber(handleValue)) {
      debounceTime = handleValue;
      handleValue = v => v;
    }

    const handleChange = value => {

      if(this.props.onChange) {
        value = directive.with(value, handleValue);

        this.props.onChange(directive.realKey, value);
        // 联动属性
        directive.refs.forEach(({ key, value }) => {
          this.props.onChange(key, value);
        });
      }
    };

    if(debounceTime) {
      return _.debounce(handleChange, debounceTime);
    }

    return handleChange;
  }

  refsNoEdit = (value) => {
    const { required, hidden } = this.props.data;

    if(value === '1') {
      return {
        required: '0',
        hidden: '0'
      }
    }

    return {
      required,
      hidden
    }
  }

  refsRequired = (value) => {
    const { hidden, readOnly } = this.props.data;

    if(value === '1') {
      return {
        hidden: '0',
        readOnly: '0'
      }
    }
    return {
      hidden,
      readOnly
    }
  }

  refsHidden = (value) => {
    const { readOnly, required } = this.props.data;

    if(value === '1') {
      return {
        required: '0',
        readOnly: '0'
      }
    }

    return {
      required,
      readOnly
    }
  }

  renderDefaultValue() { return null; }
  renderContent() { return null; }
  renderTipContent() { return null; }
  _renderVerifyContent() { return null; }
  
  renderVerifyContent() { 
    const { data } = this.props;
    const { required, validateTypes } = data;
    let varifyComponents = '';

    if(validateTypes && validateTypes.length > 0) {

        varifyComponents = validateTypes.map(type => {
        const VarifyComponent = getVarifyComponent(type);

        if(VarifyComponent) return (<VarifyComponent ecId={`${this && this.props && this.props.ecId || ''}_VarifyComponent@l6mzro@`} {...this.props}/>)
      })
    }

    return (
      <React.Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@8166n0`}>
        {_.isUndefined(required) ? null :
          <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@z0gpq5`}>
            <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@3z4f69`}
              id='text_required'
              content={getLabel('502498', '这个是必填项')}
              value={this.props.data.required}
              onChange={this.handlePropChange('required:(refs=refsRequired)')}
            />
          </Row>
        }

        {this._renderVerifyContent()}
        {varifyComponents}
      </React.Fragment>
    );
  }
  
  renderPhysicalField() {
    const { type, field, data } = this.props;
    const { fieldName, tableName, detailTable} = field;
    const { addressFieldsSelVal } = this.state;
    const newType = type.toUpperCase();

    if (newType === DATATABLE && detailTable) {
      return (
        <React.Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@lgt2z8`}>
          <FieldNameItem ecId={`${this && this.props && this.props.ecId || ''}_FieldNameItem@u0hs5r`} name={getLabel('521499', '明细子表名')} tips={getLabel('521500', '当前明细子表对应的数据库物理表的表名')} value={detailTable} />
        </React.Fragment>
      )
    }

    if (newType === ADDRESS) {
      const { province, city, district, detail } = data;
      let options = [];

      if (province.fieldName) {
        options = [
          { key: province.fieldName, showname: `${getLabel('502455','省/自治区/直辖市')}`, selected: true, },
          { key: city.fieldName, showname: `${getLabel('502456','市区')}` },
          { key: district.fieldName, showname: `${getLabel('502457','区/县')}` },
          { key: detail.fieldName, showname: `${getLabel('502450', '详细地址')}` },
        ];
      } else {
        return;
      }

      if (!addressFieldsSelVal) {
        this.setState({ addressFieldsSelVal: options[0].key });
      }

      return (
        <React.Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@fe7iac`}>
          <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@94gtuf`} className='wea-edc-physical-field'>
            <label>{getLabel('685', '字段名称')}</label>
            <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@6eicdd`}
              title={<div>{getLabel('521424', '当前字段所在数据库物理表的字段名称')}</div>}
              placement="topRight"
            />
          </Row>
          <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@iflfim`} className='wea-edc-physical-field address' gutter={8}>
            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@3lylf6`} span={12} >
              <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@5m5ndw`}
                placeholder={getLabel('521425', '点击选择')}
                options={options}
                onChange={addressFieldsSelVal => {this.setState({ addressFieldsSelVal })}}
              />
            </Col>
            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@1db49m`} span={12} >
              <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@wgtr3q`} viewAttr={1} value={this.state.addressFieldsSelVal} hasBorder={true}/>
            </Col>
            <CopyToClipboard ecId={`${this && this.props && this.props.ecId || ''}_CopyToClipboard@eg01sg`} text={this.state.addressFieldsSelVal} onCopy={success}>
                <div title={getLabel('383573', '点击复制')} className='field-icon'><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@jwcypr`} type="copy" /></div>
            </CopyToClipboard>
          </Row>
        </React.Fragment>
      )
    }
    
    if (!fieldName && newType !== FORM_HEADER) return;

    return (
      <React.Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@h3nuub`}>
        {newType !== FORM_HEADER ? 
          <FieldNameItem ecId={`${this && this.props && this.props.ecId || ''}_FieldNameItem@6f6220`} name={getLabel('685', '字段名称')} tips={getLabel('521424', '当前字段所在数据库物理表的字段名称')} value={fieldName} />
          :
          <FieldNameItem ecId={`${this && this.props && this.props.ecId || ''}_FieldNameItem@mriruz`} name={getLabel('21900', '表名')} tips={getLabel('521426', '当前表单对应的数据库物理表的表名')} value={tableName} />
        }
      </React.Fragment>
    )
  }

  render() {
    const { data, type } = this.props;
    const { title, desc, hidden, placeholder } = data;
    const ckConfig = {
      startupFocus: false,
      toolbar: [
        { name: 'styles', items: ['FontSize'] },
        { name: 'colors', items: ['TextColor', 'BGColor', 'RemoveFormat'] },
        { name: 'paragraph', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight'] },
        { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike'] },
        { name: 'links', items: ['Link', 'Unlink', '-', 'Maximize', 'Image'] },
      ],
      autoGrow_minHeight: 60,
      uploadUrl: '/api/edc/page/uploadFile4Editor',
      extraPlugins: 'image2,uploadimage,autogrow'
    };
    
    return (
      <div className={`wea-edc-props-${type}`}>
        {this.renderPhysicalField()}
        
        {_.isUndefined(title) ? null :
          <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@cttint`}>
            <label>{getLabel('502496', '标题')}</label>
            <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@ge5qzw`} inputType={'multilang'} value={title} onChange={this.handlePropChange('title')} />
          </Row>
        }

        {this.renderDefaultValue()}

        {_.isUndefined(placeholder) ? null :
          <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@m2ncv2`}>
            <label>{getLabel('127229', '提示信息')}</label>
            <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@mtpxu5`} inputType={'multilang'} value={placeholder} placeholder={getLabel('516809', '请输入')} onChange={this.handlePropChange('placeholder')} />
          </Row>
        }
        {
          _.isUndefined(desc) ? null :
            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@9kv6y8`}>
              <label>{getLabel('502497', '描述')}</label>
              <WeaRichText ecId={`${this && this.props && this.props.ecId || ''}_WeaRichText@t58krj`} ckConfig={ckConfig} value={desc} onChange={this.handlePropChange('desc')} />
            </Row>
        }

        {this.renderContent()}

        {this.renderVerifyContent()}

        {/* 解决对于较早应用字段里无hidden属性，无法设置隐藏字段 */}
        {(_.isUndefined(hidden) && !~hasReadOnlyComs.indexOf(type.toUpperCase())) ? null :
          <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@00h1zb`}>
            <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@miovt0`}
              id='text_hidden'
              content={getLabel('511745','隐藏字段')}
              value={this.props.data.hidden}
              onChange={this.handlePropChange('hidden:(refs=refsHidden)')}
            />
            <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@8t5yxg`}
              title={<div>{getLabel('511755','勾选后，该字段只有管理员及数据维护员可见，普通填写者将看不到此字段；通常适用于当你想为已提交数据设置一些特殊属性，如状态（处理/未处理）或优先级（重要/一般）。')}</div>}
              placement="topRight"
            />
          </Row>
        }
        {
          !!~hasReadOnlyComs.indexOf(type.toUpperCase()) &&
          <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@bsmafj`}>
            <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@1ejl2r`}
              content={getLabel('521081', '字段只读')}
              value={this.props.data.readOnly || '0'}
              onChange={this.handlePropChange('readOnly:(refs=refsNoEdit)')}
            />
            <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@2obkbg`}
              title={<div>{getLabel('521082', '勾选后，普通填写者将无法对字段进行编辑修改操作')}</div>}
              placement="topRight"
            />
          </Row>
        }
        {this.renderTipContent()}
      </div>
    );
  }
}

Props.defaultProps = {
  onChange: () => { }
};